#include <unistd.h>
#include <stdio.h>
#include <string.h>

/*
    读写无名管道(无名管道实际上是存在与内核空间的一个队列)
    读管道是出队操作,写管道是入队操作
    无名管道读数据后数据会被删除,如果没有读到数据则会堵塞
    写管道写溢出后也会阻塞,写满是65536字节
    测试命令: ./2.out
    结果: 第一次读管道成功,接着阻塞
*/
int main(int argc, char *argv[])
{
    int pipefd[2];
    int pipe_res;
    char write_buff[100] = "123451234512345";  //15个字节
    char read_buff[100] = {0};

    /*创建无名管道*/
    pipe_res = pipe(pipefd);
    if(pipe_res == 0)
        /*
        Linux进程会默认打开三个文件描述符：
            0 ：标准输入 stdin
            1 ：标准输出 stdout
            2 ：标准错误 stderror
        所以pipefd[0] = 3, pipefd[1] = 4
        */
        printf("pipefd[0] = %d, pipefd[1] = %d\n",pipefd[0],pipefd[1]);
    else{
        printf("创建无名管道失败!\n");
        return -1;
    }

    /*写管道*/
    write(pipefd[1], write_buff, strlen(write_buff));

    /*读管道*/
    read(pipefd[0], read_buff, 100);
    printf("读管道数据1 = %s\n", read_buff);

    /*再次读管道,会阻塞*/
    // memset(read_buff, 0 ,sizeof(read_buff));
    // read(pipefd[0], read_buff, 100);
    // printf("读管道数据2 = %s\n", read_buff);

    char data = 1;
    for(long int i = 0; i < 65537; i++){
        write(pipefd[1], &data, 1);
    }

    printf("没有写满1\n");

    close(pipefd[0]);
    close(pipefd[1]);

    return 0;
}
